/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-05 08:41:09
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 16:35:34
 * @FilePath: /operator-manager/src/pages/AccountAccessManage/RoleManage/index.tsx
 * @Description: 角色管理
 */
import AccessButton, {
  BtnAccessEnum,
  accessBtnMap,
} from '@/components/AccessBtn';
import { getRolesList, roleDelete } from '@/services';
import { ProFormText, QueryFilter } from '@ant-design/pro-components';
import { useEmotionCss } from '@ant-design/use-emotion-css';
import { useNavigate } from '@umijs/max';
import { Button, FormInstance, Popconfirm, Space, Table, message } from 'antd';
import { ColumnsType } from 'antd/es/table';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import { superManagerId } from '../constants';
import { RoleTableDataType, RoleTableEnum } from '../type.d';

//默认的分页数据
const defaultPagination = {
  page: 1,
  pageSize: 20,
};
//默认的表单数据
const defaultTableData = {
  dataList: [],
  total: 0,
};

export default function PositionManagePage() {
  const navigate = useNavigate();
  const roleSearchRef = useRef<FormInstance>();
  const [tableData, setTableData] = useState({ ...defaultTableData });
  const [paginationCurrent, setPagination] = useState({ ...defaultPagination });
  const tableAreaClass = useEmotionCss(() => {
    return {
      padding: '20px',
    };
  });

  //获取角色的列表数据
  const fetchRolesList = async (params = {}) => {
    const searchParams = {
      ...paginationCurrent,
      ...params,
    };
    const { page, ...rest } = searchParams;
    const result = await getRolesList({ data: { ...rest, pageNo: page } });
    const { dataList, totalResult } = result?.data ?? {};
    setTableData({
      dataList,
      total: totalResult,
    });
  };
  // 跳转到编辑页面
  const handleToEdit = (roleId: string | number) => {
    navigate(`/account_access_manage/role_manage/role_edit/${roleId}`);
  };
  //刷新列表
  const reloadTable = () => {
    const searchValues = roleSearchRef?.current?.getFieldsValue() ?? {};
    fetchRolesList(searchValues);
  };
  //删除角色
  const handleToDel = (roleId: string | number) => {
    console.log('调用接口删除角色', roleId);
    roleDelete({ data: { id: roleId } }).then((res) => {
      if (res?.success) {
        message.success('删除成功');
        reloadTable();
      }
    });
  };

  const columns: ColumnsType<RoleTableDataType> = [
    {
      title: 'ID',
      dataIndex: RoleTableEnum.ID,
      width: 100,
    },
    {
      title: '角色',
      dataIndex: RoleTableEnum.ROLE_NAME,
      width: 150,
    },
    {
      title: '角色描述',
      dataIndex: RoleTableEnum.ROLE_DESC,
      width: 150,
      ellipsis: {
        showTitle: true,
      },
    },
    {
      title: '创建时间',
      dataIndex: RoleTableEnum.CREATE_TIME,
      width: 150,
      render: (value) => {
        return value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : '-';
      },
    },
    {
      title: '操作',
      dataIndex: 'action',
      fixed: 'right',
      width: 150,
      render: (_, record) => {
        //超级管理员角色不能做任何操作
        return record?.id !== superManagerId ? (
          <Space>
            <AccessButton
              accessKey={accessBtnMap.get(BtnAccessEnum.ROLE_EDIT) as string}
            >
              <Button
                type="link"
                style={{ color: '#ffbd6f' }}
                key="edit"
                onClick={() => handleToEdit(record.id)}
              >
                编辑
              </Button>
            </AccessButton>
            <AccessButton
              accessKey={accessBtnMap.get(BtnAccessEnum.ROLE_DEL) as string}
            >
              <Popconfirm
                title={`确定要删除该么？删除后，拥有该角色的员工将无法正常使用系统`}
                onConfirm={() => handleToDel(record.id)}
                placement="topLeft"
              >
                <Button type="link" style={{ color: '#666' }} key="delete">
                  删除
                </Button>
              </Popconfirm>
            </AccessButton>
          </Space>
        ) : null;
      },
    },
  ];
  //跳转到添加角色页面
  const handleClickToAdd = () => {
    navigate('/account_access_manage/role_manage/role_add');
  };

  useEffect(() => {
    reloadTable();
  }, []);

  return (
    <div>
      <QueryFilter
        defaultCollapsed
        split
        formRef={roleSearchRef}
        submitter={{
          render: (_, dom) => {
            return dom.reverse();
          },
        }}
        onFinish={async (values) => {
          fetchRolesList({ ...values });
        }}
        onReset={() => {
          reloadTable();
        }}
      >
        <ProFormText name={RoleTableEnum.ROLE_NAME} label="角色" />
      </QueryFilter>
      <div className={tableAreaClass}>
        <AccessButton
          accessKey={accessBtnMap.get(BtnAccessEnum.ROLE_ADD) as string}
        >
          <Button
            type="primary"
            style={{ marginBottom: '20px' }}
            onClick={handleClickToAdd}
          >
            添加角色
          </Button>
        </AccessButton>
        <Table
          rowKey="id"
          dataSource={tableData.dataList}
          columns={columns}
          scroll={{ x: 'max-width' }}
          pagination={{
            pageSize: paginationCurrent.pageSize,
            current: paginationCurrent.page,
            pageSizeOptions: [20, 50, 100],
            showQuickJumper: true,
            showSizeChanger: true,
            onChange: (page, pageSize) => {
              setPagination({ page, pageSize });
              fetchRolesList({ page, pageSize });
            },
          }}
        />
      </div>
    </div>
  );
}
